<?php

namespace App\Http\Controllers\Admin;

use App\Models\Category;
use App\Models\Config;
use App\Models\GoodsCustomfield;
use App\Models\Order;
use App\Models\SaleUser;
use App\Models\Source;
use App\Services\CommonService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Models\OtherOrderAllocate;
use App\Models\OtherOrder;

//基础信息管理
class BasicInfoManagementController extends BaseController
{
    //品类列表
    public function categoryList(Request $request)
    {
        $input = $request->input();
        $page = $input['page'] ? $input['page'] : 1;
        $pageSize = $input['pageSize'] ? $input['pageSize'] : CommonService::PAGESIZE;
        $parentCateData = Category::where(array('parentid' => 0, 'is_delete' => Category::CATEGORY_NOT_DELETE))
            ->select('id', 'name', 'image', 'parentid', 'displayorder', 'enabled', 'rent_category', 'insurance_category', 'zlb_class', 'link')
            ->orderBy('id', 'asc')
            ->orderBy('displayorder', 'asc')
            ->paginate($pageSize);
        $parentCateData = $parentCateData ? $parentCateData->toArray() : [];
        $parentCateData = formatPage($parentCateData);
        $info = $parentCateData['data'];
        foreach ($info as $k => $v) {
            $son_type = Category::where(array('parentid' => $v['id'], 'is_delete' => Category::CATEGORY_NOT_DELETE))
                ->select('id', 'name', 'image', 'parentid', 'displayorder', 'enabled', 'rent_category', 'insurance_category', 'zlb_class', 'link')
                ->orderBy('id', 'asc')
                ->orderBy('displayorder', 'asc')
                ->get();
            $son_type = $son_type ? $son_type->toArray() : [];
            $info[$k]['children'] = $son_type;
        }
        $parentCateData['data'] = $info;
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $parentCateData);
    }

    //添加或编辑品类
    public function addOrEditCategory(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) { //添加
            if (empty($input['name'])) { //品类名称
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入品类名称');
            }
            if (empty($input['image'])) { //图片路径
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请上传封面图片');
            }
            if ($input['displayorder'] == '' || $input['displayorder'] == null) { //排序
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入排序');
            }
            if (!is_numeric($input['displayorder'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '排序只能是数字');
            }
            if ($input['addType'] == 'parent') { //添加父级
                $input['parentid'] = 0;
            } elseif ($input['addType'] == 'children') { //添加子级
                if ($input['parentid'] == '' || $input['parentid'] == null || $input['parentid'] == 0) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择一级品类');
                }
                if (empty($input['rent_category'])) { //租赁类目
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择租赁类目');
                }
                if (empty($input['insurance_category'])) { //保险类目
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择保险类目');
                }
                if (empty($input['zlb_class'])) { //租赁宝类目
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择租赁宝类目');
                }
            }
            unset($input['addType']);
            $input['is_delete'] = Category::CATEGORY_NOT_DELETE;
            $id = Category::insertGetId($input);
            if ($id) {
                $this->categoryRedisUpdate();
                //设置H5端平台分类缓存
                $this->setH5Category($id);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '添加成功');
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '添加失败');
            }
        } else { //编辑
            if (array_key_exists('displayorder', $input)) {
                if ($input['displayorder'] == '' || $input['displayorder'] == null) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入排序');
                }
                if (!is_numeric($input['displayorder'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '排序只能是数字');
                }
            }
            if (array_key_exists('image', $input)) {
                if (empty($input['image'])) { //图片路径
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请上传封面图片');
                }
            }
            if (array_key_exists('enabled', $input)) {
                if ($input['enabled'] == Category::CATEGORY_STATUS_HIDE) { //状态 1显示 0隐藏
                    $second = Category::GetSonCate($input['id']);
                    if (!empty($second)) {
                        //修改一级分类状态为隐藏时直接也隐藏二级分类状态
                        foreach ($second as $k => $v) {
                            Category::editDataById($v['id'], array('enabled' => $input['enabled']));
                            //设置H5端平台分类缓存
                            $this->setH5Category($input['id']);
                        }
                    }
                }
            }
            Category::editDataById($input['id'], $input);
            $this->categoryRedisUpdate();
            //设置H5端平台分类缓存
            $parentid = Category::where(array('id'=>$input['id']))->value('parentid');
            $parentid = $parentid == 0 ? $input['id'] : $parentid;
            $this->setH5Category($parentid);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '编辑成功');
        }
    }

    //根据id删除品类POST http://shop.cn/Admin/BasicInfoManagement/delCategory
    public function delCategory(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'id为空');
        }
        $second = Category::where(array('parentid' => $input['id'], 'is_delete' => Category::CATEGORY_NOT_DELETE))->get(); //是否删除  1是 2否
        if (!empty($second)) {
            //删除一级分类时直接也删除二级分类
            foreach ($second as $k => $v) {
                Category::editDataById($v['id'], array('is_delete' => Category::CATEGORY_IS_DELETE));
                //设置H5端平台分类缓存
                $this->setH5Category($input['id']);
            }
        }
        Category::editDataById($input['id'], array('is_delete' => Category::CATEGORY_IS_DELETE));
        //设置H5端平台分类缓存
        $parentid = Category::where(array('id'=>$input['id']))->value('parentid');
        $parentid = $parentid == 0 ? $input['id'] : $parentid;
        $this->setH5Category($parentid);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '删除成功');
    }

    //设置H5端平台分类缓存
    private function setH5Category($parentid)
    {
        $h5_first_category = Category::GetParentCate();
        Redis::set(Category::H5_FIRST_CATEGORY, json_encode($h5_first_category));

        $h5_all_second_category = Category::GetSonAllCate();
        Redis::set(Category::H5_ALL_SECOND_CATEGORY, json_encode($h5_all_second_category));

        $h5_second_category = Category::GetOne($parentid);
        $h5_second_category['children'] = Category::GetSonCate($parentid);
        Redis::hset(Category::H5_SECOND_CATEGORY, $parentid, json_encode($h5_second_category));
    }

    //定义表单项列表
    public function defineFormList(Request $request)
    {
        $input = $request->input();
        $where = [];
        $where[] = ['c.enabled', Category::CATEGORY_STATUS_DISPLAY];
        $where[] = ['c.is_delete', Category::CATEGORY_NOT_DELETE];
        $where[] = ['gc.is_delete', GoodsCustomfield::GOODS_CUSTOMFIELD_NOT_DELETE];
        if (!empty($input['name'])) {
            $where[] = ['c.name', 'like', '%' . trim($input['name']) . '%'];
        }
        if (!empty($input['field_type'])) {
            $where[] = ['gc.field_type', $input['field_type']];
        }
        $page = $input['page'] ? $input['page'] : 1;
        $pageSize = $input['pageSize'] ? $input['pageSize'] : CommonService::PAGESIZE;
        $data = GoodsCustomfield::GetDefineFormList($pageSize, $where);
        $data = formatPage($data);
        $info = $data['data'];
        foreach ($info as $k => $v) {
            $field_type = array(1 => '文本框', 2 => '单选', 3 => '多选',4=>'下拉列表'); //字段类型；1文本框，2单选，3多选
            $info[$k]['field_type'] = $field_type[$v['field_type']];
            $info[$k]['must_is'] = $v['must_is'] == 1 ? '是' : '否'; //是否为必填项；0否，1是
            $info[$k]['create_time'] = !empty($v['create_time']) ? dateFormat($v['create_time']) : '';
        }
        $data['data'] = $info;
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    //获取品类信息 http://shop.cn/Admin/BasicInfoManagement/categoryInfo
    public function categoryInfo(Request $request)
    {
        $data = Category::GetParentCate();
        foreach ($data as $k => $v) {
            $son_type = Category::GetSonCate($v['id']);
            $data[$k]['children'] = $son_type;
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    //添加或编辑定义表单项
    public function addOrEditDefineForm(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) { //添加
            if (empty($input['category_id'])) { //商品分类ID值
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择品类');
            }
            if ($input['field_order'] == '' || $input['field_order'] == null) { //字段排序
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入字段排序');
            }
            if (empty($input['field_title'])) { //字段描述
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入字段描述');
            }
            if (empty($input['field_type'])) {  //字段类型；1文本框，2单选，3多选
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择字段类型');
            }
            if (empty($input['field_val'])) {//字段值 以英文逗号的形式隔开
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入字段值');
            }
            if (!is_numeric($input['field_order'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '字段排序只能是数字');
            }
            if (!preg_match('/^[\x{4e00}-\x{9fa5}\w]+(,[\x{4e00}-\x{9fa5}\w]+)*$/u', $input['field_val'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '字段值请英文逗号的形式隔开');
            }
            $input['is_delete'] = GoodsCustomfield::GOODS_CUSTOMFIELD_NOT_DELETE;
            $input['create_time'] = time();
            $goodsCustomfield = GoodsCustomfield::where(array('category_id'=>$input['category_id'],'field_title'=>$input['field_title']))->first();
            if(!empty($goodsCustomfield)){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '该定义表单项已添加,请勿重复添加');
            }
            $res = GoodsCustomfield::addData($input);
            if ($res) {
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '添加成功');
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '添加失败');
            }
        } else { //编辑
            if (array_key_exists('field_order', $input)){
                if ($input['field_order'] == '' || $input['field_order'] == null) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入字段排序');
                }
                if (!is_numeric($input['field_order'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '字段排序只能是数字');
                }
            }
            if (array_key_exists('field_val', $input)){
                if (empty($input['field_val'])) {//字段值 以英文逗号的形式隔开
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入字段值');
                }
                if (!preg_match('/^[\x{4e00}-\x{9fa5}\w]+(,[\x{4e00}-\x{9fa5}\w]+)*$/u', $input['field_val'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '字段值请英文逗号的形式隔开');
                }
            }
            $input['update_time'] = date('Y-m-d H:i:s');
            GoodsCustomfield::editDataById($input['id'], $input);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '编辑成功');
        }
    }

    //根据id删除定义表单项
    public function delDefineForm(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'id为空');
        }
        GoodsCustomfield::editDataById($input['id'], array('is_delete' => GoodsCustomfield::GOODS_CUSTOMFIELD_IS_DELETE, 'update_time' => date('Y-m-d H:i:s')));
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '删除成功');
    }

    //订单来源列表
    public function sourceList(Request $request)
    {
        $input = $request->input();
        $where = [];
        if (!empty($input['source_name'])) {
            $where[] = ['source_name', 'like', '%' . trim($input['source_name']) . '%'];
        }
        $page = $input['page'] ? $input['page'] : 1;
        $pageSize = $input['pageSize'] ? $input['pageSize'] : CommonService::PAGESIZE;
        $data = Source::GetSourceList($pageSize, $where);
        $data = formatPage($data);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    //添加或编辑订单来源
    public function addOrEditSource(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) { //添加
            if (empty($input['source_name'])) { //订单来源名称
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入订单来源名称');
            }
            $source = Source::GetSource(array('source_name'=>$input['source_name']));
            if(!empty($source)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单来源名称不能重复');
            }
            if (empty($input['source_code'])) { //订单来源标识
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入订单来源标识');
            }
            if(!preg_match("/^(?![0-9]+$)[0-9A-Za-z]+$/",$input['source_code'])){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单来源标识只能是英文或者英文加数字');
            }
            $res = Source::addData($input);
            if ($res) {
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '添加成功');
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '添加失败');
            }
        } else { //编辑
            Source::editDataById($input['id'], $input);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '编辑成功');
        }
    }

    //租赁类目
    public function getAlipayCategory(){
        $data['rent_list'] = Category::ALIPAY_RENT_CATEGORY;
        $data['zlb_list'] = Category::ALIPAY_RENTAL_CATEGORY;
        $data['insure_list'] = Category::ALIPAY_INSURANCE_CATEGORY;
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '添加成功',$data);
    }


    public function categoryRedisUpdate(){
        $category = Category::where([['enabled',Category::CATEGORY_STATUS_DISPLAY],['is_delete',Category::CATEGORY_NOT_DELETE]])
            ->select('id','name','image','parentid')->orderBy('displayorder','asc')->get();
        $category = $category ? $category->toArray() : [];
        $data = [];
        if(!empty($category)){
            $generateTree = function ($items, $parentKey = 'parentid') {
                $tree = $temp = [];
                foreach ($items as $item) {
                    $temp[$item['id']] = $item;
                }
                foreach ($items as $item) {
                    if (isset($temp[$item[$parentKey]])) {
                        $temp[$item[$parentKey]]['sub'][] = &$temp[$item['id']];
                    } else {
                        $tree[] = &$temp[$item['id']];
                    }
                    // 下面可以去掉 pid 元素
                    unset($temp[$item['id']][$parentKey]);
                }
                return $tree;
            };
            $data = $generateTree($category);
            Redis::set(Category::REDIS_CATEGORY,json_encode($data));
        }
    }


    //分配订单
    public function riskCount(Request $request){
        $input = $request->input();
        $page = $input['page'] ? $input['page'] : 1;
        $pageSize = $input['pageSize'] ? $input['pageSize'] : CommonService::PAGESIZE;
        $data = OtherOrderAllocate::orderBy('id','asc')->where('id','>',1)->select('name','alipayRiskCount')->paginate($pageSize);

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功',$data);
    }

    //分配订单
    public function allotOrderlist(Request $request){
        $input = $request->input();
        $page = $input['page'] ? $input['page'] : 1;
        $pageSize = $input['pageSize'] ? $input['pageSize'] : CommonService::PAGESIZE;
        $data = OtherOrderAllocate::orderBy('id','asc')->where('id','>',1)->paginate($pageSize);
        $orderCreateTime = $request->input('orderCreateTime', '');

        foreach ($data as $ra) {
            if ($orderCreateTime) {
                $orderCreateTimez = explode('~', $orderCreateTime);
                $ra['totalcate']=OtherOrder::where('member_id',$ra['member_id'])->whereBetween('created_at',[$orderCreateTimez[0],$orderCreateTimez[1]])->count();
                $alipayOrder=OtherOrder::where('member_id',$ra['member_id'])->where('from',1)->whereBetween('created_at',[$orderCreateTimez[0],$orderCreateTimez[1]])->count();
                $wxOrder=OtherOrder::where('member_id',$ra['member_id'])->where('from',2)->whereBetween('created_at',[$orderCreateTimez[0],$orderCreateTimez[1]])->count();
                $ra['totalcate']=$ra['totalcate'].'(都来租支付宝'.$alipayOrder.'单,微信'.$wxOrder.')';
            }else{
                $alipayOrder=OtherOrder::where('member_id',$ra['member_id'])->where('from',1)->count();
                $wxOrder=OtherOrder::where('member_id',$ra['member_id'])->where('from',2)->count();
                $ra['totalcate']=$ra['totalcate'].'(都来租支付宝'.$alipayOrder.'单,微信'.$wxOrder.')';
            }

            if ($orderCreateTime) {
                $orderCreateTimezb = explode('~', $orderCreateTime);

                if($ra['member_id']=='202309081070080001'){
                    $Orders=OtherOrder::where('member_id',$ra['member_id'])->whereBetween('created_at',[$orderCreateTimezb[0],$orderCreateTimezb[1]])->pluck('trade_no');

                    $certNo=Order::from('sp_order_2 as o')
                        ->leftJoin('sp_member_2 as m','m.id','=','o.uid')
                        ->where('m.cert_no','>',0)
                        ->whereIn('o.trade_no',$Orders)
                        ->groupBy('m.cert_no')
                        ->pluck('m.cert_no');
                    $servername = "116.62.243.49";
                    $username = "hanzuzu";
                    $password = "rrtyiEpAzTPwbwN2";
                    $dbname = "hanzuzu";
                    $certNo=$certNo->toArray();
                    // 创建连接
                    $conn = mysqli_connect($servername, $username, $password, $dbname);
                    // 检查连接
                    if (!$conn) {
                        die("Connection failed: " . mysqli_connect_error());
                    }
                    $certNo = "'".implode("','", $certNo)."'";
                    $sql="select COUNT(*) as total_rows from sp_order_2 o left join sp_member_2 m on m.id = o.uid
                              where o.status > '10'
                       and m.cert_no  in ($certNo) group by o.id";

                    $result = $conn->query($sql);
//                    dd($result);
                    // 检查查询是否成功
//                    if (!$result) {
//                        die("Query failed: " . $conn->error);
//                    }
                    $count = mysqli_num_rows($result);
                    $conn->close();
                    $ra['successcate']=$count;
                }else{
                    $ra['successcate']=OtherOrder::where('member_id',$ra['member_id'])->where('successcate',2)->whereBetween('created_at',[$orderCreateTimezb[0],$orderCreateTimezb[1]])->count();
                }
            }else{
                if($ra['member_id']=='202309081070080001'){
                    $Orders=OtherOrder::where('member_id',$ra['member_id'])->pluck('trade_no');

                    $certNo=Order::from('sp_order_2 as o')
                        ->leftJoin('sp_member_2 as m','m.id','=','o.uid')
                        ->where('m.cert_no','>',0)
                        ->whereIn('o.trade_no',$Orders)
                        ->groupBy('m.cert_no')
                        ->pluck('m.cert_no');
                    $servername = "116.62.243.49";
                    $username = "hanzuzu";
                    $password = "rrtyiEpAzTPwbwN2";
                    $dbname = "hanzuzu";
                    $certNo=$certNo->toArray();
                    // 创建连接
                    $conn = mysqli_connect($servername, $username, $password, $dbname);
                    // 检查连接
                    if (!$conn) {
                        die("Connection failed: " . mysqli_connect_error());
                    }
                    $certNo = "'".implode("','", $certNo)."'";
                    $sql="select COUNT(*) as total_rows from sp_order_2 o left join sp_member_2 m on m.id = o.uid
                              where o.status > '10'
                       and m.cert_no  in ($certNo) group by o.id";

                    $result = $conn->query($sql);
//                    dd($result);
                    // 检查查询是否成功
//                    if (!$result) {
//                        die("Query failed: " . $conn->error);
//                    }
                    $count = mysqli_num_rows($result);
                    $conn->close();
                    $ra['successcate']=$count;
                }else{
                    $ra['successcate']=OtherOrder::where('member_id',$ra['member_id'])->where('successcate',2)->count();
                }


            }
            if ($orderCreateTime) {
                $orderCreateTimezb = explode('~', $orderCreateTime);
                $ra['open_successcate']=OtherOrder::where('member_id',$ra['member_id'])->where('is_open_success',1)->whereBetween('created_at',[$orderCreateTimezb[0],$orderCreateTimezb[1]])->count();
            }else{
                $ra['open_successcate']=OtherOrder::where('member_id',$ra['member_id'])->where('is_open_success',1)->count();
            }
            $ra['open_today']=OtherOrder::where('member_id',$ra['member_id'])->where('is_open_success',1)->whereDate('created_at', date('Y-m-d'))->count();
            $ra['week']=OtherOrder::where('member_id',$ra['member_id'])->whereBetween('created_at',[date('Y-m-d',strtotime('-7 day')),date('Y-m-d H:i:s')])->count();
            $today=OtherOrder::where('member_id',$ra['member_id'])->whereDate('created_at', date('Y-m-d'))->count();
            $alipayOrder=OtherOrder::where('member_id',$ra['member_id'])->where('from',1)->whereDate('created_at', date('Y-m-d'))->count();
            $wxOrder=OtherOrder::where('member_id',$ra['member_id'])->where('from',2)->whereDate('created_at', date('Y-m-d'))->count();
            $ra['today']=$today.'(都来租支付宝'.$alipayOrder.'单,微信'.$wxOrder.')';
            $ra['yestoday']=OtherOrder::where('member_id',$ra['member_id'])->whereDate('created_at', date('Y-m-d',strtotime('-1 day')))->count();
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功',$data);
    }

    public function updateAllotOrder(Request $request){
        $data = OtherOrderAllocate::where('id',$request['id'])->update(['weight'=>$request['weight']]);
        $dataTwo = OtherOrderAllocate::where('id',$request['id'])->update(['open_weight'=>$request['open_weight']]);
        if($data!==false&&$dataTwo!==false){
            $sum=OtherOrderAllocate::where('member_id','>',0)->sum('weight');
            OtherOrderAllocate::where('id',1)->update(['weight'=>10-$sum]);
            $sum=OtherOrderAllocate::where('member_id','>',0)->sum('open_weight');
            OtherOrderAllocate::where('id',1)->update(['open_weight'=>10-$sum]);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功',$data);
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');
    }

    //优选推送是否
    public function editOpenGoods(Request $request){
        $open_goods= OtherOrderAllocate::where('id',$request['id'])->value('open_goods');
        if($open_goods){
            OtherOrderAllocate::where('id',$request['id'])->update(['open_goods'=>0]);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
        }else{
            OtherOrderAllocate::where('id',$request['id']   )->update(['open_goods'=>1]);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');
    }


    /**
     * 基础设置
     * @param Request $request
     * @return false|string
     */
    public function editBaseSetting(Request $request){
        $input = $request->input();
        $json=json_encode($input);
        if($input['min_age']>=$input['max_age']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '最小年龄不能大于最大年龄');
        }
        $data=Config::where('id',3)->update(['value'=>$json]);
        if($data!==false){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功',$data);
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');
    }

    /**
     * 推单渠道详情
     * @return void
     */
    public function saleOrderlist(Request $request)
    {
        $orderCreateTime = $request->input('orderCreateTime', '');
        $seller_id = $request->input('member_id', '');
        if(!$seller_id){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择商家');
        }
        $day = $request->input('day', date('Y-m-d'));
        if ($orderCreateTime) {
            $orderCreateTimea = explode('~', $orderCreateTime);
            $wherea[] = ['create_time', '>=', strtotime($orderCreateTimea[0])];
            $wherea[] = ['create_time', '<=',strtotime($orderCreateTimea[1])];
        }else{
            $wherea[] = ['create_time', '>=', strtotime($day)];
            $wherea[] = ['create_time', '<=',strtotime($day)+86400];
        }

        $sale_user_ids=SaleUser::where('channel_name','<>','')->select('sale_user_id','channel_name')->get()->toArray();

        $data=[];
        foreach ($sale_user_ids as $key=>$sale){
            $push_count=Order::where('sale_user_id',$sale['sale_user_id'])->where('seller_id',$seller_id)->where($wherea)->count();
            if($push_count){
                $data[]=['push_count'=>$push_count,'day'=>$orderCreateTime?$orderCreateTime:$day,'channel_name'=>$sale['channel_name']];
            }
        }
        $array=[];
        $array['day']=$orderCreateTime?$orderCreateTime:$day;
        $array['channel_name']='自主下单';
        $array['push_count']=Order::whereNull('sale_user_id')->where('seller_id',$seller_id)->where($wherea)->count();
        array_push($data,$array);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }
}
